package edu.guigu.livedatademo;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import edu.guigu.livedatademo.databinding.ActivityLiveDataDemoBinding;

public class LiveDataDemoActivity extends AppCompatActivity {
    private ActivityLiveDataDemoBinding binding;
    private MutableLiveData<String> stringliveData = new MutableLiveData<>(); // 可被观察的LiveData数据
    private MutableLiveData<User> userLiveData = new MutableLiveData<>(); // 可被观察的LiveData数据rr
    private UserViewModel viewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityLiveDataDemoBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        viewModel = new ViewModelProvider(this).get(UserViewModel.class);
        initObserve();
        interactionControl();
    }

    private void initObserve() {
        // 设置观察者 (这里的观察者是LifecycleOwner，我们的acitivty就是，因为上层已实现此接口)
        stringliveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                binding.textView.setText(s); // 更新视图UI（当liveData数据被修改时会来回调此onchanged方法）
            }
        });

        userLiveData.observe(this, user -> {
            Toast.makeText(this, "姓名：" + user.getName() + "，年龄：" + user.getAge(), Toast.LENGTH_SHORT).show();
        });

        viewModel.getUserLiveData().observe(this, users -> {
            Log.d("TAG", "onChange: " + users.toString());
        });
    }

    private void interactionControl() {
        // 单击按钮，修改LiveData数据
        binding.buttonUiUpdate.setOnClickListener(v -> {
            stringliveData.setValue("新名称,来自UI线程的修改");// 只能在UI线程使用
            userLiveData.setValue(new User("新名称UI", 18));
            viewModel.getUserLiveData().setValue(new User("UI新名称ViewModel", 38));
        });
        // 单击按钮，修改LiveData数据
        binding.buttonNonuiUpdate.setOnClickListener(v -> {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    stringliveData.postValue("新名称,来自非UI线程的修改");// 支持在非UI线程使用
                    userLiveData.postValue(new User("新名称nonUI", 28));
                    viewModel.getUserLiveData().postValue(new User("nonUI新名称ViewModel", 38));
                }
            }).start();
        });
    }
}